/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zornav.file;

import com.transas.navmath.Pos3D;
import com.transas.zornav.data.DataSource;
import java.io.BufferedWriter;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author amalikov
 */
public class MissionPlannerDataSourceWriter implements DataSourceWriter {
	private final static Logger LOG = Logger.getLogger(MissionPlannerDataSourceWriter.class.getName());

	public MissionPlannerDataSourceWriter() {
		nf = NumberFormat.getNumberInstance(Locale.US);
		nf.setMinimumFractionDigits(6);
		nf.setMaximumFractionDigits(12);
		nf.setGroupingUsed(false);			
	}
	
	@Override
	public void process(BufferedWriter file, DataSource ds) {
		try {
			file.write(HEADER);
			file.newLine();
			
			file.write(createWayPoint(0, getWayPoint(ds, 0)));	// home point
			file.newLine();
			
			for (int i = 0; i < ds.getSize(); ++i) {
				file.write(createWayPoint(i + 1, getWayPoint(ds, i)));
				file.newLine();
			}
		} catch (IOException ex) {
			LOG.log(Level.SEVERE, null, ex);
		}
	}
	
	private String createWayPoint(int index, Pos3D wpt) {
		StringBuilder str = new StringBuilder();
		str.append(Integer.toString(index));
		str.append("\t");
		str.append(index == 0? "1\t0\t16\t0\t0\t0\t0\t" : "0\t3\t16\t0\t0\t0\t0\t");
		str.append(nf.format(wpt.lat));
		str.append("\t");
		str.append(nf.format(wpt.lon));
		str.append("\t");
		str.append(nf.format(wpt.alt));
		str.append("\t1");
		return str.toString();
	}

	private Pos3D getWayPoint(DataSource ds, int index) {
		return new Pos3D(
			ds.getValue(ds.getHandle("Latitude"), index),
			ds.getValue(ds.getHandle("Longitude"), index),
			ds.getValue(ds.getHandle("Altitude"), index));
	}
	
	private static final String HEADER = "QGC WPL 110";
	private NumberFormat nf;
}
